package SocketTest;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

public class UIDemo {
    private Frame win;
    private TextField textField;
    private JButton button1;
    private JButton button2;

    public UIDemo(Socket socket) throws IOException {
        win = new MyFrame();
        textField = new TextField(30);
        button1 = new JButton("接收");
        button2 = new JButton("发出");

        win.add(button2);
        win.add(textField);
        win.add(button1);

//        InputStream in = socket.getInputStream();
        OutputStream out = socket.getOutputStream();

        button1.addActionListener(new Listener(socket.getInputStream()));

        button2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String text = textField.getText();
                System.out.println(text);
                try {
                    out.write(text.getBytes());
                    if(text.startsWith("exit"))
                        System.exit(0);
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
        });

        win.setVisible(true); //这边不加会导致第一次打开窗口时无图标显示
    }
}
